package com.onetech.adrewards.free.fragments;

import java.util.List;

import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import twitter4j.conf.Configuration;
import twitter4j.conf.ConfigurationBuilder;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.AsyncTask.Status;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;

import com.google.analytics.tracking.android.EasyTracker;
import com.onetech.adrewards.free.R;
import com.onetech.adrewards.free.adapters.ListSocialShareAdapter;
import com.onetech.adrewards.free.customviews.LoadMoreListView;
import com.onetech.adrewards.free.customviews.LoadMoreListView.OnLoadMoreListener;
import com.onetech.adrewards.free.dialogs.ShareFacebookDialog;
import com.onetech.adrewards.free.dialogs.ShareTwitterDialog;
import com.onetech.adrewards.free.models.CommonModel;
import com.onetech.adrewards.free.objects.SocialShareDTO;
import com.onetech.adrewards.free.utils.AdrewadsUtils;
import com.onetech.adrewards.free.utils.PackageHelper;

public class SocialShareFragment extends BaseFragment implements
		OnLoadMoreListener, OnItemClickListener {

	private LoadMoreListView mListView;
	// private View mNoPointHistoryView = null;
	// private TextView mTitleBar=null;

	private ListSocialShareAdapter mAdapter;
	private LoadPointHistory mLoadSocialShare = null;

	protected int pageNo = 1;

	private static String twitterShareText = "";

	// twitter
	public static SharedPreferences mSharedPref;
	private static final String SHARED_PREF = "android_twitter";
	private static final String USER_SCREEN_NAME = "tw_user_id";
	private static final String USER_NAME = "tw_user_name";
	private static final String USER_PIC = "tw_user_pic";
	public static final String PREF_KEY_SECRET = "oauth_token_secret";
	public static final String PREF_KEY_TOKEN = "oauth_token";

	public static Twitter mTwitter;
	public static final String CONSUMER_KEY = "vrW3aRHhAfrDgH5G0XgiAAPuM";
	public static final String CONSUMER_SECRET = "2w9Byx0PRHtiEva3HYIaoQi2ttcdFuJmvf5GvaTtxw38qbH2lb";
	public static final String CALLBACK_URL = "twittercallback://socialshare";
	private static RequestToken requestToken;
	public static final String IEXTRA_OAUTH_VERIFIER = "oauth_verifier";
	public static final String IEXTRA_OAUTH_TOKEN = "oauth_token";

	// end twitter

	// Line Social
	private String mLineAppId = "jp.naver.line.android";
	private static final int LINE_INTENT_CODE = 0;
	public static final String LINE_PACKAGE_NAME = "jp.naver.line.android";
	public static final String LINE_CLASS_NAME = "jp.naver.line.android.activity.selectchat.SelectChatActivity";

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		if (mView == null) {
			mView = inflater.inflate(R.layout.social_share_activity_layout, container,
					false);
			initView();
			initListener();			

		} else {
			((ViewGroup) mView.getParent()).removeView(mView);
		}
		return mView;
	}
	private void initShareTwitter() {
		ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
		configurationBuilder.setOAuthConsumerKey(CONSUMER_KEY);
		configurationBuilder.setOAuthConsumerSecret(CONSUMER_SECRET);
		Configuration configuration = configurationBuilder.build();
		mTwitter = new TwitterFactory(configuration).getInstance();

		mSharedPref = getActivity().getSharedPreferences(SHARED_PREF, Context.MODE_PRIVATE);

		Uri uri = getActivity().getIntent().getData();
		if (uri != null && uri.toString().startsWith(CALLBACK_URL)) {
			String verifier = uri.getQueryParameter(IEXTRA_OAUTH_VERIFIER);
			try {
				AccessToken accessToken = mTwitter.getOAuthAccessToken(
						requestToken, verifier);
				Editor e = mSharedPref.edit();
				e.putString(PREF_KEY_TOKEN, accessToken.getToken());
				e.putString(PREF_KEY_SECRET, accessToken.getTokenSecret());
				// User user = mTwitter.verifyCredentials();
				// e.putString(USER_SCREEN_NAME, user.getScreenName());
				// e.putString(USER_NAME, user.getName());
				// e.putString(USER_PIC, user.getOriginalProfileImageURL());
				e.commit();

				ShareTwitterDialog mShareTwitterDialog = new ShareTwitterDialog(
						getActivity(), "", twitterShareText);
				mShareTwitterDialog.show();

			} catch (Exception e) {
				getBaseNewActivity().showToast(e.getMessage());
			}
		}
	}
	private void initView() {
		mListView = (LoadMoreListView) mView.findViewById(R.id.listSocial);
		mListView.setVisibility(View.GONE);
		mAdapter = new ListSocialShareAdapter(getActivity());
		mListView.setAdapter(mAdapter);
		initNotFoundAndLoadingView();
		showNotFoundOrLoadingView(false, true);
	}

	private void initListener() {
		mListView.setOnItemClickListener(this);
		initRetryButtonListener();
	}

	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btnRetry:
			pageNo = 1;
			mListView.setVisibility(View.VISIBLE);
			showNotFoundOrLoadingView(false, true);
			loadSocialShare();
			break;
		default:
			super.onClick(v);
			break;
		}
	}

	@Override
	public void onResume() {
		super.onResume();
		initShareTwitter();
		AdrewadsUtils.checkUId();
		getBaseNewActivity().getUserInfo();
		if (mAdapter != null && mAdapter.getCount() < 1) {
			loadSocialShare();
		}		
	}

	private void loadSocialShare() {
		if (mLoadSocialShare == null
				|| mLoadSocialShare.getStatus() == Status.FINISHED) {
			mLoadSocialShare = new LoadPointHistory();
			mLoadSocialShare.execute();
		}
	}	

	private class LoadPointHistory extends
			AsyncTask<Void, Void, List<SocialShareDTO>> {
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			showNotFoundOrLoadingView(false, true);
			// showNoHistory(false);
		}

		@Override
		protected List<SocialShareDTO> doInBackground(Void... params) {
			try {
				return CommonModel.getInstance().getSocialShareBonus();
			} catch (Exception e) {
				return null;
			}
		}

		@Override
		protected void onPostExecute(List<SocialShareDTO> result) {
			super.onPostExecute(result);
			try {
				if (result != null) {
					if (result.size() < 1) {
						if (mAdapter.getCount() < 1) {
							showNotFoundOrLoadingView(false, false);
							// showNoHistory(true);
							mListView.setVisibility(View.GONE);
						} else {
							// showNoHistory(false);
							showNotFoundOrLoadingView(false, false);
							mListView.setVisibility(View.VISIBLE);
						}
					} else {
						if (pageNo == 1) {
							mAdapter.updateSocialList(result);
						} else {
							mAdapter.insertSocialList(result);
						}
						pageNo++;
						showNotFoundOrLoadingView(false, false);
						mListView.setVisibility(View.VISIBLE);
					}
				} else {
					if (mAdapter.getCount() < 1) {
						showNotFoundOrLoadingView(true, false);
						// showNoHistory(false);
						mListView.setVisibility(View.GONE);
					} else {
						// showNoHistory(false);
						showNotFoundOrLoadingView(false, false);
						mListView.setVisibility(View.VISIBLE);
					}
				}
			} catch (Exception e) {
			}
			mListView.onLoadMoreComplete();
		}
	}

	@Override
	public void onLoadMore() {
		loadSocialShare();
	}

	@Override
	public void onStart() {
		super.onStart();
		// The rest of your onStart() code.
		try {
			EasyTracker.getInstance(getActivity()).activityStart(getActivity()); // Add this
																// method.
		} catch (Exception e) {
		}
	}

	@Override
	public void onStop() {
		super.onStop();
		// The rest of your onStop() code.
		try {
			EasyTracker.getInstance(getActivity()).activityStop(getActivity()); // Add this
																// method.
		} catch (Exception e) {
		}
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		SocialShareDTO item = mAdapter.getItem(position);
		if (item != null) {
			if (item.type.equals("6")) { // Line cointype=6
				shareLineTextSocail(item.shareText);
				return;
			}
			if (item.type.equals("7")) { // fb cointype=7
				Intent shareFBDialog = new Intent(getActivity(),
						ShareFacebookDialog.class);
				shareFBDialog.putExtra(Intent.EXTRA_TEXT, item.shareText);
				startActivity(shareFBDialog);
				return;
			}
			if (item.type.equals("8")) { // Twitter cointype=8
				twitterShareText = item.shareText;
				LoginTwitter();
			}
		}
	}

	/**
	 * check if the account is authorized
	 * 
	 * @return
	 */
	private boolean isConnected() {
		return mSharedPref.getString(PREF_KEY_TOKEN, null) != null;
	}

	private void LoginTwitter() {

		if (isConnected()) {
			showTwitterDialog();
		} else {
			signinTwitter();
		}
	}

	private void showTwitterDialog() {
		ShareTwitterDialog mShareTwitterDialog = new ShareTwitterDialog(
				getActivity(), "", twitterShareText);
		mShareTwitterDialog.show();
	}

	private void signinTwitter() {

		try {
			requestToken = mTwitter.getOAuthRequestToken(CALLBACK_URL);
			getBaseNewActivity().showToast(getActivity().getString(R.string.twitter_please_login));
			this.startActivity(new Intent(Intent.ACTION_VIEW, Uri
					.parse(requestToken.getAuthenticationURL())));
		} catch (TwitterException e) {
			getBaseNewActivity().showToast(e.getErrorMessage());
		}

	}


	private void shareLineTextSocail(String text) {
		String TAG = "[LineKitANE] ShareText -";
		if (PackageHelper.getInstance(getActivity()).isInstalled(
				mLineAppId)) {

			try {

				CommonModel.getInstance().doSocialCoin("6");

				Intent intent = new Intent(Intent.ACTION_SEND);
				intent.setClassName(LINE_PACKAGE_NAME, LINE_CLASS_NAME);
				intent.setType("text/plain");
				intent.putExtra(Intent.EXTRA_TEXT, text);
				startActivity(intent);
				// String uri = "line://msg/text/" + text;
				// Intent intent = Intent.parseUri(uri,
				// Intent.URI_INTENT_SCHEME);
				// intent.setType("text/plain");
				// startActivity(intent);
			} catch (Exception e) {
				Log.e(TAG, e.toString());
			}
		} else {
			getBaseNewActivity().showToast(getActivity().getString(R.string.line_social_not_installed_message));
		}
	}

	public void updateUser() {
		getBaseNewActivity().getUserInfo();
	}

}
